/**
 * DistanceIDSorter.java
 * ************************** 
 * @date May 6, 2011
 * @author Michele Tamburini
 * 
 * **************************
 */
package gossipServices.bootstraping.tman.rankingMethods.rankingComparators;

import gossipServices.basic.nodeDescriptors.NodeDescriptor;
import gossipServices.bootstraping.tman.rankingMethods.RankingPair;

/**
 * Description: 
 * This class implements the RankingComparator. 
 * It's able to compare two RankingPair(s) in input: o1 and o2. 
 * It defines the notion of distance between two RankingPairs by the formula:
 * 	Math.abs(baseNode.getNodeID() - o1.getNode().getNodeID())
 * If applied to a Collection of RankingPair(s) it will sort it
 * according to the increasing value of the distances. 
 */
public class DistanceIDSorter implements RankingComparator {
	
	NodeDescriptor baseNode;	
	
	public DistanceIDSorter(NodeDescriptor baseNode){
		this.baseNode = baseNode;
	}

	@Override
	public int compare(RankingPair o1, RankingPair o2) {
		Long d1 = calculateDistance(o1);
		Long d2 = calculateDistance(o2);
		return d1.compareTo(d2);
	}

	/**
	 * @param o1
	 * @return
	 */
	protected Long calculateDistance(RankingPair o1) {
		int abs = Math.abs(baseNode.getNodeID() - o1.getNode().getNodeID());
		return new Long(Math.min( Long.MAX_VALUE - abs, abs));
	}

}
